<template>
  <div>
    <el-row
      :gutter="10"
      style="margin-left: 5px; margin-top: 5px; margin-right: 5px"
    >
      <!--    分类信息-->
      <el-col :span="8">
        <el-card style="height: 780px; overflow: auto">
          <div class="show_title">案卷类别：</div>
          <!-- 搜索框 -->
          <!--          <el-input-->
          <!--            placeholder="输入关键字进行过滤"-->
          <!--            v-model="filterText"-->
          <!--          ></el-input>-->
          <!-- el-tree -->
          <el-tree
            v-if="classList.length > 0"
            class="filter-tree"
            :data="classList"
            :props="{ label: 'className', children: 'children' }"
            :default-expand-all="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            style="margin-top: 10px"
          ></el-tree>
          <!-- 无数据时的提示 -->
          <el-empty v-else description="暂无数据"></el-empty>
        </el-card>
      </el-col>
      <!--    案卷信息-->
      <el-col :span="8">
        <el-card style="height: 780px" v-loading="volumeLoading">
          <div slot="header" class="search-header">
            <div class="show_title">案卷目录：</div>
            <el-input
              v-model="volumeQueryParams.vname"
              placeholder="搜索案卷"
              clearable
              @keyup.enter.native="searchVolume"
              class="my_input"
            />
            <div class="button-group">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="searchVolume"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetVolume"
                >重置</el-button
              >
            </div>
          </div>
          <div class="engs-container" ref="volumeContainer">
            <div
              class="eng-row"
              v-for="volume in volumeList"
              :key="volume.id"
              @click="selectVolume(volume)"
              :class="{ selected: volume === selectedVolume }"
            >
              <i class="folder-icon volume-folder-icon"></i>
              <span class="folder-name">{{ volume.vname }}</span>
            </div>
          </div>
          <div class="pagination-container">
            <!-- 分页信息 -->
            <el-pagination
              @size-change="handleSizeChangeVolume"
              @current-change="handleCurrentChangeVolume"
              :current-page.sync="volumeQueryParams.pageNum"
              :page-size.sync="volumeQueryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="volumeTotal"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
      <!--    文件信息-->
      <el-col :span="8">
        <el-card style="height: 780px" v-loading="fileLoading">
          <div slot="header" class="search-header">
            <div class="show_title">文件列表：</div>
            <el-input
              v-model="fileQueryParams.filename"
              placeholder="搜索文件"
              clearable
              @keyup.enter.native="searchFile"
              class="my_input"
            />
            <div class="button-group">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="searchFile"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetFile"
                >重置</el-button
              >
            </div>
          </div>
          <div class="engs-container" ref="fileContainer">
            <div
              class="eng-row"
              v-for="file in fileList"
              :key="file.id"
              @click="selectFile(file)"
              @dblclick="openFile(file)"
              :class="{ selected: file === selectedFile }"
            >
              <i class="folder-icon file-folder-icon"></i>
              <span class="folder-name">{{ file.filename }}</span>
            </div>
          </div>
          <div class="pagination-container">
            <!-- 分页信息 -->
            <el-pagination
              @size-change="handleSizeChangeFile"
              @current-change="handleCurrentChangeFile"
              :current-page.sync="fileQueryParams.pageNum"
              :page-size.sync="fileQueryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="fileTotal"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row
      :gutter="10"
      style="margin-left: 5px; margin-top: 5px; margin-right: 5px"
    >
      <el-row v-if="currentInfo === 'volume'">
        <el-col :span="24">
          <volume-info :volume-info="selectedVolume"></volume-info>
        </el-col>
      </el-row>

      <el-row v-else-if="currentInfo === 'file'">
        <el-col :span="24">
          <file-info :file-info="selectedFile"></file-info>
        </el-col>
      </el-row>

      <el-row v-else-if="currentInfo === null">
        <el-col :span="24">
          <el-empty description="无案卷/文件信息"></el-empty>
        </el-col>
      </el-row>
    </el-row>

    <!-- 文件显示弹窗 -->
    <el-dialog
      :visible.sync="pdfDialogVisible"
      title="文件详情"
      :width="dialogWidth"
      center
    >
      <embed
        :src="pdfUrl"
        type="application/pdf"
        width="100%"
        height="1000px"
      />
    </el-dialog>
    <el-dialog
      :visible.sync="imgDialogVisible"
      title="文件详情"
      :width="dialogWidth"
      center
    >
      <embed :src="blobImage" type="image/jpeg" width="100%" height="1000px" />
    </el-dialog>
  </div>
</template>

<script>
import { listClass } from "@/api/system/class";
import {
  listVolumeinfo,
  selectModuleVolumeInfoByClassIds,
} from "@/api/system/volumeinfo";
import { getPdf, getType, listFileInfo } from "@/api/system/fileinfo";
import VolumeInfo from "@/views/system/search/volumeInfo";
import FileInfo from "@/views/system/search/fileInfo";

export default {
  components: {
    VolumeInfo,
    FileInfo,
  },
  data() {
    return {
      // 类别表格数据
      classList: [],
      // 查询参数
      queryParams: {
        parentId: null,
        className: null,
      },
      // 搜索关键字
      filterText: "",
      currentInfo: null,

      volumeTotal: 0, //案卷总数
      volumeList: [], //案卷列表
      selectedVolume: null,
      volumeLoading: false,
      volumeQueryParams: {
        pageNum: 1,
        pageSize: 20,
        classIds: [],
        vname: null,
      },

      fileTotal: 0, //文件总数
      fileList: [], //文件列表
      selectedFile: null,
      fileLoading: false,
      fileQueryParams: {
        pageNum: 1,
        pageSize: 20,
        volumeid: null,
        filename: null,
      },
      blobImage: "", //图片url
      pdfUrl: "", // 存储PDF文件的URL地址
      pdfDialogVisible: false, // 控制弹窗的显示与隐藏
      imgDialogVisible: false, // 控制弹窗的显示与隐藏
      dialogWidth: "70%", // 弹窗的宽度
      dialogHeight: "80vh",
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询类别列表 */
    getList() {
      this.loading = true;
      listClass(this.queryParams)
        .then((response) => {
          this.classList = this.handleTree(
            response.data,
            "classId",
            "parentId"
          );
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 过滤节点 */
    filterNode(value, data) {
      if (!value || !data.label) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 节点点击事件处理 */
    handleNodeClick(data) {
      // 递归查找所有最小类别节点
      const smallestClasses = this.findSmallestClasses(data);
      // 处理最小类别节点列表，例如打印或进行其他操作
      console.log("最小类别列表：", smallestClasses);
      this.volumeQueryParams.classIds = smallestClasses;
      this.getVolumeList();
    },
    /** 递归查找最小类别节点 */
    findSmallestClasses(node) {
      if (!node || !node.children || node.children.length === 0) {
        // 如果节点为空或没有子节点，则当前节点为最小类别
        return [node.classId];
      }
      let smallestClasses = [];
      for (const child of node.children) {
        const childSmallestClasses = this.findSmallestClasses(child);
        smallestClasses = smallestClasses.concat(childSmallestClasses);
      }
      return smallestClasses;
    },

    //获取案卷信息
    getVolumeList() {
      this.volumeLoading = true;
      console.log(this.volumeQueryParams);
      selectModuleVolumeInfoByClassIds(this.volumeQueryParams)
        .then((response) => {
          setTimeout(() => {
            this.volumeList = response.rows;
            this.volumeTotal = response.total;
            this.volumeLoading = false;
          }, 300);
        })
        .catch((error) => {
          this.$message.error("获取案卷信息失败:" + error);
          this.volumeLoading = false;
        });
    },
    //获取案卷信息
    // getVolumeList() {
    //   this.volumeLoading = true;
    //   listVolumeinfo(this.volumeQueryParams).then((response) => {
    //     setTimeout(() => {
    //       this.volumeList = response.rows;
    //       this.volumeTotal = response.total;
    //       this.volumeLoading = false;
    //     }, 300);
    //   })
    //     .catch((error) => {
    //       this.$message.error("获取案卷信息失败:" + error);
    //       this.volumeLoading = false;
    //     });
    // },
    searchVolume() {
      this.volumeQueryParams.pageNum = 1;
      this.getVolumeList();
    },
    resetVolume() {
      // this.volumeQueryParams.classIds = null
      this.volumeQueryParams.vname = null;
      if (this.volumeQueryParams.classIds.length != 0) {
        this.getVolumeList();
      }
    },
    selectVolume(volume) {
      this.selectedVolume = volume;
      this.currentInfo = "volume";
      this.fileQueryParams.volumeid = volume.id;
      this.getFileList();
    },
    handleSizeChangeVolume(pageSize) {
      this.volumeQueryParams.pageSize = pageSize;
      this.getVolumeList();
    },
    handleCurrentChangeVolume(currentPage) {
      this.volumeQueryParams.pageNum = currentPage;
      this.getVolumeList();
    },

    //获取文件信息
    getFileList() {
      this.fileLoading = true;
      listFileInfo(this.fileQueryParams)
        .then((response) => {
          setTimeout(() => {
            this.fileList = response.rows;
            this.fileTotal = response.total;
            this.fileLoading = false;
          }, 300);
        })
        .catch((error) => {
          this.$message.error("获取文件信息失败:" + error);
          this.fileLoading = false;
        });
    },
    searchFile() {
      this.fileQueryParams.pageNum = 1;
      this.getFileList();
    },
    resetFile() {
      // this.fileQueryParams.volumeid = null;
      this.fileQueryParams.filename = null;
      if (this.fileQueryParams.volumeid.length != 0) {
        this.getFileList();
      }
    },
    selectFile(file) {
      this.selectedFile = file;
      this.currentInfo = "file";
    },
    // 双击文件名打开文件
    openFile(file) {
      getType(file).then((response) => {
        if (response.toString() === "pdf") {
          this.openPDF(file);
        } else if (response.toString() === "jpg") {
          this.openImg(file);
        }
      });
    },
    //打开图片
    openImg(file) {
      this.fileForm = file; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
      getPdf(this.fileForm)
        .then((response) => {
          const blob = new Blob([response], { type: "image/jpeg" });
          this.blobImage = URL.createObjectURL(blob);
          this.imgDialogVisible = true; // 显示弹窗
        })
        .catch((error) => {
          console.error("获取图片时出错:", error);
          // 可以添加错误处理逻辑，比如显示一个错误提示框等
        });
    },
    //打开PDF
    openPDF(file) {
      this.fileForm = file; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
      getPdf(this.fileForm)
        .then((response) => {
          const blob = new Blob([response], { type: "application/pdf" });
          this.pdfUrl = URL.createObjectURL(blob);
          this.pdfDialogVisible = true; // 显示弹窗
        })
        .catch((error) => {
          console.error("Error occurred while fetching the PDF:", error);
          // 可以添加错误处理逻辑，比如显示一个错误提示框等
        });
    },
    handleSizeChangeFile(pageSize) {
      this.fileQueryParams.pageSize = pageSize;
      this.getFileList();
    },
    handleCurrentChangeFile(currentPage) {
      this.fileQueryParams.pageNum = currentPage;
      this.getFileList();
    },
  },
};
</script>

<style>
.search-header {
  display: flex;
  align-items: center;
}
.show_title {
  font-weight: bold;
  font-size: 20px;
  color: rgb(26, 115, 198);
}
.my_input {
  margin-left: auto;
  width: 37%;
  margin-right: 5px;
}
.button-group {
  display: flex;
  align-items: center;
  margin-left: 10px;
}
.engs-container {
  height: 600px;
  overflow-y: auto;
}
.eng-row {
  flex-basis: 100%;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.eng-row:hover {
  cursor: pointer;
  background-color: #e5f3ff;
}
.pagination-container {
  margin-top: 10px;
}
.folder-icon {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  margin-right: 5px;
  background-size: cover;
}
.folder-name {
  flex-grow: 1;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.volume-folder-icon {
  background-image: url("~@/assets/icons/folder/volume-icon.png");
}
.file-folder-icon {
  background-image: url("~@/assets/icons/folder/file-icon.png");
}
/* 选中状态的样式 */
.selected {
  /*box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);*/
  background-color: #cce8ff;
}
</style>
